<template>
  <div
    class="mt-24px w-full flex flex-row justify-center items-center slider"
    @mousemove="handleMouseMove"
  >
    <button
      :class="[
        'w-20px h-20px transform transition ',
        moveWidth > 0 ? 'hover:scale-110' : 'opacity-50'
      ]"
      @click="handleMoveNumber(-0.1)"
    >
      <img src="@/assets/hot-left.png" alt="" class="w-full h-full" />
    </button>
    <div class="mx-25px w-360px slider-custom-style">
      <div class="w-full h-32px flex items-center">
        <div class="flex-1 h-6px bg-[#e4e7ed] rounded-3px relative">
          <div
            :style="moveWidthPercent"
            @mousedown="handleMouseDown"
            class="absolute top-[-50%] left-0 w-40px h-12px bg-[#838DAC] rounded-6px translate-x-[-50%] hover:scale-120 transition cursor-grab active:cursor-grabbing"
          ></div>
        </div>
      </div>
    </div>
    <button
      :class="[
        'w-20px h-20px rotate-180 transform  transition',
        moveWidth < 1 ? ' hover:scale-110' : 'opacity-50'
      ]"
      @click="handleMoveNumber(0.1)"
    >
      <img src="@/assets/hot-left.png" alt="" class="w-full h-full" />
    </button>
  </div>
</template>
<script setup>
import { computed } from 'vue'
import { useEventListener, useVModel } from '@vueuse/core'
const emits = defineEmits(['update:modelValue'])
const props = defineProps({
  modelValue: Number
})
const moveWidth = useVModel(props, 'modelValue', emits)
const parentWidth = 360
let isDown = false
const moveWidthPercent = computed(() => {
  const percent = moveWidth.value * 100
  return 'left:' + percent + '%'
})
const handleMoveNumber = (number) => {
  moveWidth.value = Math.min(Math.max(moveWidth.value + number, 0), 1)
}
const sliderMove = {
  lastX: 0,
  currentX: 0,
  get diff() {
    return this.currentX - this.lastX
  }
}
const handleMouseDown = (e) => {
  isDown = true
  sliderMove.lastX = e.pageX
}
const handleMouseUp = () => {
  isDown = false
}
useEventListener(document, 'mouseup', handleMouseUp)
const handleMouseMove = (e) => {
  if (!isDown) return
  sliderMove.currentX = e.pageX
  const diff = sliderMove.diff
  const moveWidthTemp = moveWidth.value * parentWidth + diff
  moveWidth.value = Math.min(Math.max(moveWidthTemp, 0), 360) / parentWidth
  sliderMove.lastX = sliderMove.currentX
}
</script>
<style lang="less" scoped>
.slider {
  -webkit-touch-callout: none;
  -moz-user-select: none; /*火狐*/
  -webkit-user-select: none; /*webkit浏览器*/
  -ms-user-select: none; /*IE10*/
  -khtml-user-select: none; /*早期浏览器*/
  user-select: none;
}
</style>
